package com.yue92.datalife.service.impl;

import com.yue92.datalife.model.Record;
import com.yue92.datalife.repository.RecordItemRepository;
import com.yue92.datalife.service.IAnalysisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.time.LocalDate;
import java.util.*;

@Service
public class AnalysisServiceImpl implements IAnalysisService {

    @Autowired
    private RecordItemRepository recordItemRepository;

    @Override
    public AnalysisResult getData(LocalDate date, Record record, Boolean cumulate) {
        AnalysisResult result = new AnalysisResult();
        int monthLast = 1;
        LocalDate snapshotYearLast = date;
        List<Integer> monthValueList = new ArrayList<>();
        List<Integer> seriesDataLast = new ArrayList<>();
        LocalDate now = LocalDate.now();
        do {
            Integer sum = recordItemRepository.sum(record.getId(), date);
            if (date.getMonth().getValue() == monthLast) {
                if (record.getAllowCumulate()) {
                    monthValueList.add(sum);
                } else if (sum != null && sum > 0) {
                    monthValueList = Arrays.asList(sum);
                }
            } else {
                int total = monthValueList.stream().mapToInt(value -> value == null ? 0 : value).sum();
                seriesDataLast.add(total);
                if (cumulate && record.getAllowCumulate()) {
                    monthValueList = new ArrayList<Integer>() {{
                        add(total);
                        add(sum);
                    }};
                } else {
                    monthValueList = new ArrayList<Integer>() {{
                        add(sum);
                    }};
                }

                monthLast++;
            }

            date = date.plusDays(1);
            if (date.compareTo(now) > 0) {
                break;
            }
        } while (date.getYear() == snapshotYearLast.getYear());

        int latest = monthValueList.stream().mapToInt(value -> value == null ? 0 : value).sum();
        if (latest > 0) {
            seriesDataLast.add(latest);
        }

        result.setSeriesName(String.valueOf(snapshotYearLast.getYear()));
        result.setSeriesData(seriesDataLast);

        return result;
    }

    @Override
    public int getGirdX(int max) {
        int girdX = 25;
        if (max >= 100000) {
            girdX = 60;
        } else if (max >= 10000) {
            girdX = 50;
        } else if (max >= 1000) {
            girdX = 40;
        } else if (max >= 100) {
            girdX = 30;
        }

        return girdX;
    }
}
